<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>编辑批次</span>
        <el-button @click="goBack">返回</el-button>
      </div>
    </template>

    <el-form :model="editForm" label-width="120px" ref="editFormRef" :rules="editRules" style="max-width: 600px">
      <el-form-item label="学年" prop="academicYear">
        <el-date-picker
            v-model="editForm.academicYear"
            type="year"
            placeholder="选择学年"
            style="width: 100%"
            value-format="YYYY"
        />
      </el-form-item>
      <el-form-item label="困难等级" prop="difficultyLevel">
        <el-select v-model="editForm.difficultyLevel" placeholder="请选择困难等级" style="width: 100%">
          <el-option label="一般困难" :value="1" />
          <el-option label="困难" :value="2" />
          <el-option label="特别困难" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="申请开始时间" prop="applyStart">
        <el-date-picker
            v-model="editForm.applyStart"
            type="date"
            placeholder="选择申请开始时间"
            style="width: 100%"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="申请截止时间" prop="applyDeadline">
        <el-date-picker
            v-model="editForm.applyDeadline"
            type="date"
            placeholder="选择申请截止时间"
            style="width: 100%"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="登记截止时间" prop="registerDeadline">
        <el-date-picker
            v-model="editForm.registerDeadline"
            type="date"
            placeholder="选择登记截止时间"
            style="width: 100%"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitEdit">保存</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>

    <!-- 衣服类型管理 -->
    <el-divider content-position="left">
      <span style="font-size: 16px; font-weight: bold;">衣服类型管理</span>
    </el-divider>

    <!-- 已关联的衣服类型 -->
    <div class="section-title">已关联的衣服类型</div>
    <div v-loading="linkedLoading" class="clothing-cards">
      <el-empty v-if="linkedClothingList.length === 0" description="暂无关联的衣服类型" />
      <div v-else class="card-grid">
        <el-card 
          v-for="item in linkedClothingList" 
          :key="item.id" 
          class="clothing-card"
          shadow="hover"
        >
          <img :src="item.image || '/default.png'" class="card-image" />
          <div class="card-content">
            <div class="card-name">{{ item.name }}</div>
            <el-tag :type="getGenderTagType(item.genderLimit)" size="small">
              {{ formatGender(item.genderLimit) }}
            </el-tag>
          </div>
          <el-button 
            type="danger" 
            size="small" 
            @click="removeClothing(item.id)"
            style="width: 100%; margin-top: 10px"
          >
            移除
          </el-button>
        </el-card>
      </div>
    </div>

    <!-- 所有衣服类型 -->
    <div class="section-title" style="margin-top: 30px;">所有衣服类型</div>
    
    <!-- 搜索框 -->
    <el-form :inline="true" style="margin-bottom: 15px;">
      <el-form-item label="名称">
        <el-input
            v-model="searchParams.name"
            placeholder="请输入衣服名称"
            clearable
            @keyup.enter="searchAvailableClothing"
            style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="searchParams.gender" placeholder="请选择性别" clearable style="width: 150px">
          <el-option label="女" :value="0" />
          <el-option label="男" :value="1" />
          <el-option label="通用" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchAvailableClothing">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <div v-loading="availableLoading" class="clothing-cards">
      <el-empty v-if="availableClothingList.length === 0" description="暂无衣服类型" />
      <div v-else class="card-grid">
        <el-card 
          v-for="item in availableClothingList" 
          :key="item.id" 
          class="clothing-card"
          shadow="hover"
        >
          <img :src="item.image || '/default.png'" class="card-image" />
          <div class="card-content">
            <div class="card-name">{{ item.name }}</div>
            <el-tag :type="getGenderTagType(item.genderLimit)" size="small">
              {{ formatGender(item.genderLimit) }}
            </el-tag>
          </div>
          <el-button 
            v-if="isLinked(item.id)"
            type="info" 
            size="small" 
            disabled
            style="width: 100%; margin-top: 10px"
          >
            已添加
          </el-button>
          <el-button 
            v-else
            type="primary" 
            size="small" 
            @click="addClothing(item.id)"
            style="width: 100%; margin-top: 10px"
          >
            添加
          </el-button>
        </el-card>
      </div>
    </div>

    <!-- 分页 -->
    <el-pagination
        :current-page="searchParams.page"
        :page-size="searchParams.limit"
        :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="availableTotal"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        @update:current-page="(val) => searchParams.page = val"
        @update:page-size="(val) => searchParams.limit = val"
        style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { _getBatchById, _updateBatch, _saveClothingStyle, _deleteClothingStyle } from '@/api/batch'
import { _getClothingStylePage, _getListByBatchId } from '@/api/clothingStyle'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const batchId = ref(Number(route.params.id))

// 编辑表单
const editFormRef = ref(null)
const editForm = ref({
  id: null,
  academicYear: '',
  difficultyLevel: null,
  applyStart: '',
  applyDeadline: '',
  registerDeadline: ''
})

// 表单验证规则
const editRules = {
  academicYear: [
    { required: true, message: '请选择学年', trigger: 'change' }
  ],
  difficultyLevel: [
    { required: true, message: '请选择困难等级', trigger: 'change' }
  ],
  applyStart: [
    { required: true, message: '请选择申请开始时间', trigger: 'change' }
  ],
  applyDeadline: [
    { required: true, message: '请选择申请截止时间', trigger: 'change' }
  ],
  registerDeadline: [
    { required: true, message: '请选择登记截止时间', trigger: 'change' }
  ]
}

// 已关联的衣服类型
const linkedClothingList = ref([])
const linkedLoading = ref(false)

// 可添加的衣服类型
const availableClothingList = ref([])
const availableTotal = ref(0)
const availableLoading = ref(false)

// 搜索参数
const searchParams = ref({
  page: 1,
  limit: 12,
  name: '',
  gender: null
})

// 格式化性别
const formatGender = (gender) => {
  const map = {
    0: '女',
    1: '男',
    2: '通用'
  }
  return map[gender] || '-'
}

// 性别标签类型
const getGenderTagType = (gender) => {
  const map = {
    0: 'danger',
    1: 'primary',
    2: 'success'
  }
  return map[gender] || 'info'
}

// 格式化日期
const formatDate = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 返回列表
const goBack = () => {
  router.push('/batch/list')
}

// 获取批次详情
const getBatchDetail = () => {
  _getBatchById(batchId.value).then(res => {
    if (res.code === 200) {
      const data = res.data.batch
      editForm.value = {
        id: data.id,
        academicYear: String(data.academicYear || ''),
        difficultyLevel: data.difficultyLevel,
        applyStart: formatDate(data.applyStart),
        applyDeadline: formatDate(data.applyDeadline),
        registerDeadline: formatDate(data.registerDeadline)
      }
    } else {
      ElMessage.error(res.message || '获取批次信息失败')
    }
  }).catch(err => {
    console.error('获取批次详情失败:', err)
    ElMessage.error('获取批次信息失败')
  })
}

// 提交编辑
const submitEdit = () => {
  editFormRef.value.validate((valid) => {
    if (valid) {
      const submitData = {
        id: editForm.value.id,
        academicYear: Number(editForm.value.academicYear),
        difficultyLevel: editForm.value.difficultyLevel,
        applyStart: editForm.value.applyStart,
        applyDeadline: editForm.value.applyDeadline,
        registerDeadline: editForm.value.registerDeadline
      }
      
      _updateBatch(submitData).then(res => {
        if (res.code === 200) {
          ElMessage.success('更新成功')
        } else {
          ElMessage.error(res.message || '更新失败')
        }
      }).catch(err => {
        console.error('更新失败:', err)
        ElMessage.error('更新失败')
      })
    }
  })
}

// 获取已关联的衣服类型
const getLinkedClothing = () => {
  linkedLoading.value = true
  _getListByBatchId(batchId.value).then(res => {
    if (res.code === 200) {
      linkedClothingList.value = res.data.clothingStyleList || []
    } else {
      ElMessage.error(res.message || '获取已关联衣服类型失败')
    }
  }).catch(err => {
    console.error('获取已关联衣服类型失败:', err)
    ElMessage.error('获取已关联衣服类型失败')
  }).finally(() => {
    linkedLoading.value = false
  })
}

// 判断衣服是否已关联
const isLinked = (clothingId) => {
  return linkedClothingList.value.some(item => item.id === clothingId)
}

// 获取所有衣服类型
const getAvailableClothing = () => {
  availableLoading.value = true
  _getClothingStylePage(searchParams.value).then(res => {
    if (res.code === 200) {
      availableClothingList.value = res.data.records || []
      availableTotal.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取衣服类型失败')
    }
  }).catch(err => {
    console.error('获取衣服类型失败:', err)
    ElMessage.error('获取衣服类型失败')
  }).finally(() => {
    availableLoading.value = false
  })
}

// 搜索衣服
const searchAvailableClothing = () => {
  searchParams.value.page = 1
  getAvailableClothing()
}

// 重置搜索
const resetSearch = () => {
  searchParams.value = {
    page: 1,
    limit: 12,
    name: '',
    gender: null
  }
  getAvailableClothing()
}

// 添加衣服类型
const addClothing = (clothingId) => {
  _saveClothingStyle(batchId.value, [clothingId]).then(res => {
    if (res.code === 200) {
      ElMessage.success('添加成功')
      getLinkedClothing()
      getAvailableClothing()
    } else {
      ElMessage.error(res.message || '添加失败')
    }
  }).catch(err => {
    console.error('添加失败:', err)
    ElMessage.error('添加失败')
  })
}

// 移除衣服类型
const removeClothing = (clothingId) => {
  _deleteClothingStyle(batchId.value, [clothingId]).then(res => {
    if (res.code === 200) {
      ElMessage.success('移除成功')
      getLinkedClothing()
      getAvailableClothing()
    } else {
      ElMessage.error(res.message || '移除失败')
    }
  }).catch(err => {
    console.error('移除失败:', err)
    ElMessage.error('移除失败')
  })
}

// 分页变化
const handlePageChange = (page) => {
  searchParams.value.page = page
  getAvailableClothing()
}

const handleSizeChange = (size) => {
  searchParams.value.limit = size
  searchParams.value.page = 1
  getAvailableClothing()
}

// 初始化
onMounted(() => {
  getBatchDetail()
  getLinkedClothing()
  getAvailableClothing()
})
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.section-title {
  font-size: 15px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
}

.clothing-cards {
  min-height: 200px;
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.clothing-card {
  .card-image {
    width: 100%;
    height: 150px;
    object-fit: cover;
    border-radius: 4px;
  }

  .card-content {
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-name {
    font-size: 14px;
    font-weight: bold;
    color: #303133;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right: 10px;
  }
}
</style>

